﻿using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;
using OA.Bll.Authority;
using OA.Log;


namespace OA.Web.Authority
{
    public partial class UserGrant : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "window.parent.changewin();", true);
            strinfo.InnerHtml = "";
            strinfo.Visible = false;

            if (!IsPostBack)
            {
                UserHandle.InitModule("Mod_UsersManage");
                if (!UserHandle.ValidationHandle(RGP_Tag.Browse))
                {
                    Session["ErrorNum"] = "0";
                    Response.Redirect("~/Error.aspx");
                }
                else
                {
                    btn_saverole.Attributes.Add("OnClick", "getdata()");
                    if (Request.QueryString["uid"] != null && Request.QueryString["name"] != null)
                    {
                        UNAME.Text = Request.QueryString["name"];
                        UID.Text = Request.QueryString["uid"];
                        BindRole();
                        //BindModuleType();
                        //RolePanel.Visible = false;
                    }
                }
            }
        }

        ///// <summary>
        ///// 绑定分组数据
        ///// </summary>
        //protected void BindModuleType()
        //{
        //    BLL.RGP_Modules MTbll = new BLL.RGP_Modules();
        //    DataSet ds = MTbll.GetModuleTypeList("");
        //    ModuleTypeView.DataSource = ds;
        //    ModuleTypeView.DataBind();
        //}

        ///// <summary>
        ///// 获取模块权限列表
        ///// </summary>
        //protected void BindModules()
        //{
        //    if (TID.Text != "")
        //    {
        //        BLL.RGP_Modules Mbll = new BLL.RGP_Modules();
        //        DataSet ds = Mbll.GetModuleList2(TID.Text);
        //        ModuleView.DataSource = ds;
        //        ModuleView.DataBind();

        //        if (ds.Tables[0].Rows.Count == 0)
        //        {
        //            btn_AllSave.Visible = false;
        //        }
        //        else
        //        {
        //            btn_AllSave.Visible = true;
        //        }
        //    }
        //    else
        //    {
        //        btn_AllSave.Visible = false;
        //        ModuleView.DataSource = null;
        //        ModuleView.DataBind();
        //    }
        //}

        protected void BindRole()
        {
            UserInfoPresenter bll = new UserInfoPresenter();
            RoleList.Items.Clear();
            ArrayList rid = bll.GetUserRoleArray(int.Parse(UID.Text));
            string strwhere = "";
            for (int i = 0; i < rid.Count; i++)
            {
                string[] r = rid[i].ToString().Split(',');
                if(!string.IsNullOrEmpty(r[0]))
                {
                    RoleList.Items.Add(new ListItem(r[1], r[0]));
                    strwhere += r[0] + ",";
                }
            }
            if (strwhere != "")
            {
                OldRoleList.Text = strwhere.Substring(0, strwhere.Length - 1);
                strwhere = "not Id in(" + OldRoleList.Text + ")";
            }

            RolesPresenter bll2 = new RolesPresenter();
            FromRoleList.DataSource = bll2.GetRoleList(strwhere, "");
            FromRoleList.DataTextField = "RoleName";
            FromRoleList.DataValueField = "Id";
            FromRoleList.DataBind();
        }

        protected void ModuleType_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditView")
            {
                TID.Text = e.CommandArgument.ToString();
                //BindModules();
            }
        }

        protected void ModuleView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                AuthorityDirPresenter ad = new AuthorityDirPresenter();
                ModulesPresenter modulebll = new ModulesPresenter();
                RolesPresenter rolebll = new RolesPresenter();

                CheckBoxList authorityListGrant = (CheckBoxList)e.Row.FindControl("AuthorityList_Grant");
                CheckBoxList authorityListDeny = (CheckBoxList)e.Row.FindControl("AuthorityList_Deny");
                Label labID = (Label)e.Row.FindControl("lab_ID");
                Label labVerify = (Label)e.Row.FindControl("lab_Verify");

                DataSet ds = ad.GetAuthorityList("", "order by AuthorityOrder asc");
                DataSet malds = modulebll.GetAuthorityList(int.Parse(labID.Text));
                DataSet ralds = rolebll.GetUserAuthorityList(int.Parse(UID.Text), int.Parse(labID.Text));

                int n = ds.Tables[0].Rows.Count;//系统权限个数

                string[] vstate = new string[n];

                //获取系统配置的权限列表，如果模块没有该权限，则禁用该权限
                for (int i = 0; i < n; i++)
                {
                    authorityListGrant.Items.Add(new ListItem(ds.Tables[0].Rows[i]["AuthorityName"].ToString(), ds.Tables[0].Rows[i]["AuthorityTag"].ToString()));
                    authorityListDeny.Items.Add(new ListItem(ds.Tables[0].Rows[i]["AuthorityName"].ToString(), ds.Tables[0].Rows[i]["AuthorityTag"].ToString()));
                    authorityListGrant.Items[i].Enabled = false;
                    authorityListDeny.Items[i].Enabled = false;
                    for (int k = 0; k < malds.Tables[0].Rows.Count; k++)
                    {
                        if ((ds.Tables[0].Rows[i]["AuthorityTag"].ToString() == malds.Tables[0].Rows[k]["AuthorityTag"].ToString()))
                        {
                            authorityListGrant.Items[i].Enabled = true;
                            authorityListDeny.Items[i].Enabled = true;
                            break;
                        }
                    }
                    vstate[i] = "0";//初始状态数组;
                }
                authorityListGrant.DataBind();

                //将模块权限付值
                for (int j = 0; j < ralds.Tables[0].Rows.Count; j++)
                {
                    for (int l = 0; l < authorityListGrant.Items.Count; l++)
                    {
                        if (ralds.Tables[0].Rows[j]["AuthorityTag"].ToString() == authorityListGrant.Items[l].Value)
                        {
                            if (ralds.Tables[0].Rows[j]["Flag"].ToString().ToLower() == "true")
                            {
                                if (authorityListGrant.Items[l].Enabled)
                                    vstate[l] = "1";
                                //权限允许
                                authorityListGrant.Items[l].Selected = true;
                                break;
                            }
                            else
                            {
                                if (authorityListDeny.Items[l].Enabled)
                                    vstate[l] = "1";
                                //权限禁止权限
                                authorityListDeny.Items[l].Selected = true;
                                break;
                            }
                        }
                    }
                }

                labVerify.Text = TypeParse.StringArrayToString(vstate, ',');
            }
        }

        //protected void ModuleView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        //{
        //    ArrayList list = new ArrayList();//建立事务列表
        //    BLL.RGP_Roles Rolebll = new BLL.RGP_Roles();
        //    CheckBoxList calg = (CheckBoxList)this.ModuleView.Rows[e.NewSelectedIndex].Cells[1].FindControl("AuthorityList_Grant");
        //    CheckBoxList cald = (CheckBoxList)this.ModuleView.Rows[e.NewSelectedIndex].Cells[1].FindControl("AuthorityList_Deny");
        //    Label lab_Verify = (Label)this.ModuleView.Rows[e.NewSelectedIndex].Cells[0].FindControl("lab_Verify");
        //    string[] vstate = lab_Verify.Text.Split(',');//获取原始状态

        //    for (int i = 0; i < calg.Items.Count; i++)
        //    {
        //        if (calg.Items[i].Enabled)
        //        {
        //            if (calg.Items[i].Selected)
        //            {
        //                if (vstate[i] != "1")//检查数据有没有变化
        //                {
        //                    string item = string.Empty;
        //                    item = item + UID.Text + "|"
        //                        + this.ModuleView.DataKeys[e.NewSelectedIndex].Values[0].ToString() + "|"
        //                        + calg.Items[i].Value + "|1";//设置为1，加入允许权限
        //                    list.Add(item);
        //                }
        //            }
        //            else if (cald.Items[i].Selected)
        //            {
        //                string item = string.Empty;
        //                item = item + UID.Text + "|"
        //                    + this.ModuleView.DataKeys[e.NewSelectedIndex].Values[0].ToString() + "|"
        //                    + cald.Items[i].Value + "|0";//设置为0，加入禁止权限
        //                list.Add(item);
        //            }
        //            else
        //            {
        //                if (vstate[i] != "0")//检查数据有没有变化
        //                {
        //                    string item = string.Empty;
        //                    item = item + UID.Text + "|"
        //                        + this.ModuleView.DataKeys[e.NewSelectedIndex].Values[0].ToString() + "|"
        //                        + cald.Items[i].Value + "|2";//设置为0，删除权限
        //                    list.Add(item);
        //                }
        //            }
        //        }
        //    }

        //    if (Rolebll.UpdateUserAuthority(list))
        //    {
        //        BindModules();
        //        strinfo.InnerHtml = JScript.errinfo("更新成功！");
        //        strinfo.Visible = true;
        //    }
        //    else
        //    {
        //        strinfo.InnerHtml = JScript.errinfo("更新失败！");
        //        strinfo.Visible = true;
        //    }
        //}

        protected void btn_AllSave_Click(object sender, EventArgs e)
        {
            //BLL.RGP_Roles Rolebll = new BLL.RGP_Roles();

            //ArrayList list = new ArrayList();//建立事务列表
            //for (int i = 0; i <= ModuleView.Rows.Count - 1; i++)
            //{
            //    CheckBoxList calg = (CheckBoxList)this.ModuleView.Rows[i].Cells[1].FindControl("AuthorityList_Grant");
            //    CheckBoxList cald = (CheckBoxList)this.ModuleView.Rows[i].Cells[1].FindControl("AuthorityList_Deny");
            //    Label lab_Verify = (Label)this.ModuleView.Rows[i].Cells[0].FindControl("lab_Verify");
            //    string[] vstate = lab_Verify.Text.Split(',');//获取原始状态

            //    for (int j = 0; j < calg.Items.Count; j++)
            //    {
            //        if (calg.Items[j].Selected)
            //        {
            //            if (vstate[j] != "1")//检查数据有没有变化
            //            {
            //                string item = string.Empty;
            //                item = item + UID.Text + "|"
            //                    + this.ModuleView.DataKeys[i].Values[0].ToString() + "|"
            //                    + calg.Items[j].Value + "|1";//设置为1，加入允许权限
            //                list.Add(item);
            //            }
            //        }
            //        else if (cald.Items[j].Selected)
            //        {
            //            string item = string.Empty;
            //            item = item + UID.Text + "|"
            //                + this.ModuleView.DataKeys[i].Values[0].ToString() + "|"
            //                + cald.Items[j].Value + "|0";//设置为0，加入禁止权限
            //            list.Add(item);
            //        }
            //        else
            //        {
            //            if (vstate[j] != "0")//检查数据有没有变化
            //            {
            //                string item = string.Empty;
            //                item = item + UID.Text + "|"
            //                    + this.ModuleView.DataKeys[i].Values[0].ToString() + "|"
            //                    + cald.Items[j].Value + "|2";//设置为0，删除权限
            //                list.Add(item);
            //            }
            //        }
            //    }
            //}

            //if (Rolebll.UpdateUserAuthority(list))
            //{
            //    BindModules();
            //    strinfo.InnerHtml = JScript.errinfo("设置成功！");
            //    strinfo.Visible = true;
            //}
            //else
            //{
            //    strinfo.InnerHtml = JScript.errinfo("设置操作失败！");
            //    strinfo.Visible = true;
            //}
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DropDownList1.SelectedIndex == 0)
            {
                ModelPanel.Visible = true;
                RolePanel.Visible = false;
            }
            else
            {
                BindRole();
                ModelPanel.Visible = false;
                RolePanel.Visible = true;
            }
        }

        protected void btn_saverole_Click(object sender, EventArgs e)
        {
            string s = Request.Form["TRoleList"].ToString();

            UserInfoPresenter bll = new UserInfoPresenter();
            ArrayList ar = new ArrayList();//加加表
            ArrayList dr = new ArrayList();//删除表

            if (s != "")
            {
                string[] str = s.Substring(0, s.Length - 1).Split(',');
                string[] ostr = OldRoleList.Text.ToString().Split(',');
                for (int i = 0; i < str.Length; i++)
                {
                    if (!TypeParse.IsStringArray(str[i], ostr))
                    {
                        //不存在则添加到插入记录列表
                        ar.Add(UID.Text + "," + str[i]);
                    }
                }

                for (int i = 0; i < ostr.Length; i++)
                {
                    if (!TypeParse.IsStringArray(ostr[i], str))
                    {
                        //不存在则添加到删除记录列表
                        dr.Add(UID.Text + "," + ostr[i]);
                    }
                }
            }
            else
            {
                //如果提交角色为空则删除该用户的所有角色
                string[] ostr = OldRoleList.Text.Split(',');
                for (int i = 0; i < ostr.Length; i++)
                {
                    //不存在则添加到删除记录列表
                    dr.Add(UID.Text + "," + ostr[i]);
                }
            }

            try
            {
                if (ar.Count != 0) { bll.AddUserRole(ar); }
                if (dr.Count != 0) { bll.DeleteUserRole(dr); }
                BindRole();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
            }
        }
        protected void ModuleView_RowCommand(object sender, GridViewCommandEventArgs e)
        {

        }
    }
}
